package com.hontech.kaltaapp.device.event

import com.hontech.kaltaapp.device.RecvFrame
import com.hontech.kaltaapp.device.codec.ByteView
import com.hontech.kaltaapp.device.codec.Uint16
import com.hontech.kaltaapp.device.codec.Uint32
import com.hontech.kaltaapp.device.codec.Uint8
import com.hontech.kaltaapp.utils.log
import com.hontech.kaltaapp.utils.postEvent
import com.hontech.kaltaapp.utils.toHex4

class DeviceStatus (
    version: Uint16,
    ctrl: Uint16,
    flowCount: Uint16,
    waterTemp: Uint32,
    steamTemp: Uint32,
    steamKpa: Uint16,
    sensor: Uint16,
    draw: Uint8,
    water: Uint8,
    steam: Uint8
) {

    val appVersion = version.value.toHex4()
    val ctrlStatus = PartsCtrlStatus(ctrl.value)
    val flow = flowCount.value
    val water = TempStatus(waterTemp.value)
    val steam = TempStatus(steamTemp.value)
    val kpa = steamKpa.value
    val sensorStatus = SensorStatus(sensor.value)
    val drawInfo = drawTaskInfo(draw.value)
    val waterInfo = waterTaskInfo(water.value)
    val steamInfo = steamTaskInfo(steam.value)
}


private fun drawTaskInfo(state: Int): String {
    return when (state) {
        0 -> "抽水中"
        1 -> "超时"
        2 -> "停止"
        3 -> "空闲"
        else -> "状态未知:$state"
    }
}

private fun waterTaskInfo(state: Int): String {
    return when (state) {
        0 -> "加热中"
        1 -> "空闲"
        2 -> "停止"
        3 -> "超时"
        4 -> "故障"
        else -> "状态未知:$state"
    }
}

private fun steamTaskInfo(state: Int): String {
    return when (state) {
        0 -> "加热中"
        1 -> "空闲"
        2 -> "停止"
        3 -> "超时"
        4 -> "故障"
        else -> "状态未知:$state"
    }
}

private var deviceStatus: DeviceStatus? = null

fun status(): DeviceStatus {
    return deviceStatus ?: throw IllegalStateException("没有收到状态")
}

fun onRecvStatus(frame: RecvFrame) {
    val version = Uint16()
    val ctrl = Uint16()
    val flow = Uint16()
    val waterTemp = Uint32()
    val steamTemp = Uint32()
    val steamKpa = Uint16()
    val sensor = Uint16()
    val draw = Uint8()
    val water = Uint8()
    val steam = Uint8()
    frame.parseNotify(version, ctrl, flow, waterTemp, steamTemp, steamKpa, sensor, draw, water, steam)
    val status = DeviceStatus(version, ctrl, flow, waterTemp, steamTemp, steamKpa, sensor, draw, water, steam)
    deviceStatus = status
    postEvent(status)
}

fun onLog(frame: RecvFrame) {
    val bw = ByteView()
    frame.parseNotify(bw)
    log("LOG:${bw}")
}